package com.hengxinguotong.zhihuichengjian.ui.document;

import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.DocumentListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Document;
import com.hengxinguotong.zhihuichengjian.bean.DocumentRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/12/6.
 */

public class DocumentMenuActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.document_lv)
    PullToRefreshListView documentLv;
    private int pageIndex = 1;
    private Document document;
    private List<Document> documents;
    private DocumentListAdapter documentAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document_menu);
        ButterKnife.bind(this);
        document = (Document) getIntent().getSerializableExtra("document");
        if(document.getName().length() > 12){
            titleTv.setText(document.getName().substring(0, 11) + "...");
        }else{
            titleTv.setText(document.getName());
        }
        getDocumentList("加载中…");
        documentLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Document document = documents.get(position - 1);
                Intent intent = new Intent();
                if (document.getType() == 3) {
                    intent.setClass(DocumentMenuActivity.this, DocumentListActivity.class);
                    intent.putExtra("document", document);
                    startActivity(intent);
                } else if (document.getType() == 0){
                    intent.setAction(Intent.ACTION_VIEW);
                    String url = document.getPath().replace("type=2", "type=1");
                    intent.setData(Uri.parse(url));
                    if (intent.resolveActivity(getPackageManager()) != null) {
                        final ComponentName componentName = intent.resolveActivity(getPackageManager());
                        // 打印Log   ComponentName到底是什么
                        Log.e("wl", "componentName = " + componentName.getClassName());
                        startActivity(Intent.createChooser(intent, "请选择浏览器"));
                    } else {
                        showToast("没有匹配的程序");
                    }
                }
            }
        });
        documentLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getDocumentList(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getDocumentList(null);
            }
        });
    }

    private void getDocumentList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("pageNum", pageIndex);
            jsonObject.put("type", document.getType() + "");
            jsonObject.put("id", document.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/dataManagement/queryListByCtructionId/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (documentLv.isRefreshing()) {
                    documentLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    DocumentRes commonRes = gson.fromJson(json, DocumentRes.class);
                    addData(commonRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
                if (documentLv.isRefreshing()) {
                    documentLv.onRefreshComplete();
                }
            }
        });
    }

    private void addData(List<Document> datas) {
        if (pageIndex == 1) {
            if (datas.size() == 0) {
                showEmptyView(documentLv);
            } else {
                dismissEmptyView();
            }
            documents = datas;
            documentAdapter = new DocumentListAdapter(this, documents);
            documentLv.setAdapter(documentAdapter);
            if (datas.size() == Utils.ONCECOUNT) {
                documentLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            documents.addAll(datas);
            documentAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            documentLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @OnClick({R.id.iv_back})
    public void onClick(View v) {
        finish();
    }
}
